from pyglet.gl import *
from bipy import engine, entity, scenes, components

class TestScene(scenes.Scene):

    def on_scene_enter(self):
        install_list = ['viewmanager']
        for comp_name in install_list:
            comp_class = components.get(comp_name)
            if comp_class:
                engine.add_component( comp_class() )
        
        comp_class = components.get('imagemanager')
        engine.add_component( comp_class() )
        
        engine.images.get('background.png')
                
        # Create some views
        vm = engine.viewmanager
        self.v = vm.new_view(self, screen_pos=(0,0), screen_size=(320, 480))
        self.v2 = vm.new_view(self, screen_pos=(320,0), screen_size=(320,480))
        # Using the engine's viewmanager component, push the views.
        vm.push_views( [self.v, self.v2] )
        # Create some entities   
        self.entities = []
        for i in xrange(100):
            self.entities.append(entity.Entity())

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        self.v.zoom = max(0.1, min(2.0, self.v.zoom - dy * 0.01))
        self.v2.zoom = max(0.1, min(2.0, self.v2.zoom + dy * 0.01))
    
    def draw_entities(self):
        for ent in self.entities:
                ent.draw()
                
    def draw_axis(self):
        glPushMatrix()
        # Draw axis reference
        glLineWidth(3.0)
        glBegin(GL_LINES)
        glColor3f(1.0, 0.0, 0.0)
        glVertex3f(-100.0, 0.0, 0.0)
        glVertex3f(100.0, 0.0, 0.0)
        
        glColor3f(0.0, 1.0, 0.0)
        glVertex3f(0.0, -100.0, 0.0)
        glVertex3f(0.0, 100.0, 0.0)
        
        glColor3f(0.0, 0.0, 1.0)
        glVertex3f(0.0, 0.0, -100.0)
        glVertex3f(0.0, 0.0, 100.0)
        glEnd()
        glPopMatrix()
        
    def on_scene_leave(self):
        engine.viewmanager.pop_views()
        
    def on_draw(self):
        # Handle the 'on_draw' event
        # This is invoked under the context ofthe viewports (GL_MODELVIEW)
        # maintained by the scene.
        # TODO: draw all entities that are visible to the camera
        # Clear buffer
        engine.clear()
        vm = engine.viewmanager
        # Render all current views
        views = vm.get_views()
        if views:
            for view in views:
                view.set_viewport()
                self.draw_entities()
                self.draw_axis()

        # Render FPS counter
        engine.viewmanager.reset_view()
        engine.draw_fps()
        engine.flip()
        
    def on_update(self, dt):
        for entity in self.entities:
            pass#entity.on_update(dt)
        
scene_class = TestScene